package com.cn.ycy.entity.result;

import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * @author qiss
 */
public class Message {
    private static final String BUNDLE_NAME = "message";

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

    private Message() {
    }

    public static ResultCode getRCode(String key, Object... params) {
        String value = null;
        if (null == params) {
            value = getString(key);
        } else {
            value = getString(key, params);
        }
        return buildResultCode(value);
    }

    private static ResultCode buildResultCode(String value) {
        int code = 0;
        String msg = null;
        if (StringUtils.isNotBlank(value)) {
            String[] vlas = value.split("-");
            if (vlas.length > 1) {
                if (StringUtils.isNotBlank(vlas[0])) {
                    code = Integer.parseInt(vlas[0]);
                }
                if (StringUtils.isNotBlank(vlas[1])) {
                    msg = vlas[1];
                }
            }
        }
        if (code > 0) {
            return ResultCode.valueOf(code, msg);
        } else {
            return ResultCode.IS_NULL;
        }
    }

    private static String getString(String key) {
        try {
            return RESOURCE_BUNDLE.getString(key);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }

    private static String getString(String key, Object... params) {
        try {
            return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params);
        } catch (MissingResourceException e) {
            return '!' + key + '!';
        }
    }

}
